#include"../../source/server/rpcServer.hpp"

void onConnectionCb(BaseConnection::ptr conn)
{
    LOG_DEBUG << "触发连接成功回调";
}

void onRpcRequest(BaseConnection::ptr conn, RPCRequest::ptr msg, BaseProtocol::ptr handlerProtocol)
{
    LOG_DEBUG << "触发onMessage回调:";
    LOG_DEBUG << "id = " << msg->getId() << " mtype = " << (int)msg->getType();
    LOG_DEBUG << "method = " << msg->getMethod();
    auto param = msg->getParameters();
    int left = param["left"].asInt();
    int right = param["right"].asInt();
    LOG_DEBUG << "参数left = " << left << "  right = " << right;

    auto respon = MessageFactory::create<RpcResponse>();
    respon->setId();
    respon->setType(MSG_Type::RPC_RES);
    respon->setRcode(RCode::OK);
    Json::Value val;
    val[KEY_RESULT] = left + right;
    respon->setResult(val);

    std::string out = handlerProtocol->serialize(respon);
    if (!out.empty())
    {
        if (conn->connected())
        {
            conn->send(out);
        }
    }
}

void Add(const Json::Value& parameters, Json::Value& result)
{
    result["sum"] = parameters["num1"].asInt() + parameters["num2"].asInt();
}

int main()
{
    Init_logger("DEBUG", "/srv/log/jsonRpc/", "test-server2", 1024 * 1024);

    RpcServer::ptr server = std::make_shared<RpcServer>(Address("0.0.0.0", 8082), Address("127.0.0.1", 8081));
    server->connectRegister();

    CallDescription::ptr add = std::make_shared<CallDescription>();
    add->setCallName("Add");
    add->setCall(Add);
    CallDescription::parametersTV parametersType = {{"num1", ParameterType::INTEGRAL}, {"num2", ParameterType::INTEGRAL}};
    add->setParametersType(parametersType);
    add->setAddress(Address("127.0.0.1", 8082));

    server->registerMethod(add);

    server->start();

    // RpcRoute::ptr rpc_route = std::make_shared<RpcRoute>();

    // // 添加method
    // CallDescription::ptr add = std::make_shared<CallDescription>();
    // add->setCallName("Add");
    // add->setCall(Add);
    // CallDescription::parametersTV parametersType = {{"num1", ParameterType::INTEGRAL}, {"num2", ParameterType::INTEGRAL}};
    // add->setParametersType(parametersType);

    // rpc_route->setMethodToFunc("Add", add);

    // // 消息类型 --- 分类调度
    // auto dispatcher = DispatcherFactory::create();
    // dispatcher->setCallBack<RPCRequest>(MSG_Type::RPC_REQ, std::bind(&RpcRoute::onRpcReauest, rpc_route.get(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

    // // 服务端 （往上）
    // auto server = NetFactory::creater<MuduoServer>("0.0.0.0", 8080, "test-server", true);
    // server->setHandlerProtocol(ProtocolFactory::create<LvProtocol>());
    // server->setConnCb(onConnectionCb);
    // server->setMessageHander(std::bind(&Dispatcher::onMessage, dispatcher.get(), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    // server->setIoThreads(3);
    // server->start();
    return 0;
}